package com.ldk.api.handler;

import com.ldk.api.ApiVersion;
import com.ldk.api.CheckToken;
import com.ldk.api.Consts;
import com.ldk.api.ErrorCode;
import com.ldk.api.RequestPlatform;
import com.ldk.api.ResponseObject;
import com.ldk.api.ResponseResult;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.DateUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.base.framework.util.baidu.RouteMatrixApi;
import com.ldk.base.framework.util.baidu.routematrix.RouteMatrixRequestParms;
import com.ldk.base.framework.util.baidu.routematrix.RouteMatrixResponseParmsResult;
import com.ldk.framework.entity.*;
import com.ldk.framework.enums.BillingMode;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.ServiceCode;
import com.ldk.framework.enums.TradePayStatus;
import com.ldk.framework.enums.TripNoType;
import com.ldk.framework.enums.TripStatus;
import com.ldk.framework.service.*;

import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 包车业务模块
 *
 * @author xiangwl
 * 2017年3月9日
 * com.ldk.api.handler
 * BCRequestHandler
 */
public class CJTRequestHandler extends BZBaseRequestHandler {
    /**
     * 包车业务流程
     * 用户端：1、发布行程 2、取消行程 3、支付行程 4、评价行程
     * 司机端：1、接受行程 2、拒绝行程 3、已发车 4、确认用户上车 5结束行程
     */
    @Autowired
    private ICjtCityService cjtCityService;
    @Autowired
    private ICjtRoadService cjtRoadService;
    @Autowired
    private ICjtSchedulService cjtSchedulService;
    @Autowired
    private IServiceTripService serviceTripService;
    @Autowired
    private ICompanypermitService companypermitService;

    @Autowired
    private IUserService userService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private ICJTServiceTripService cJTServiceTripService;
    @Autowired
    private ITenpayService tenpayService;
    @Autowired
    private IAlipayService alipayService;
    @Autowired
    private IServiceConfigService serviceConfigService;
    @Autowired
    private IServiceTripCrewsService serviceTripCrewsService;


    /**
     * 获取城际通开通城市列表
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getCityList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "getCityList");
        if (!checkRequireParms(parms, "serviceCode")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        CjtCity query = new CjtCity();
        query.setEnabled(true);

        List<CjtCity> regionList = cjtCityService.selectList("", query);
        ResponseResult.success(response, regionList);

        return response;
    }


    /**
     * 根据城市名称，返回已开通城际通城市编码，（有则返回对应编码，没有开通则返回默认贵阳编码）
     * cityName:城市名称
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject queryCityCode(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "queryCityCode");
        if (!checkRequireParms(parms, "cityName")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String cityName = ConvertUtil.parseString(parms.get("cityName"));
        if (StringUtils.isBlank(cityName)) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        CjtCity query = new CjtCity();
        query.setEnabled(true);
        query.setCity(cityName);
        List<CjtCity> regionList = cjtCityService.selectList("", query);
        if (regionList != null && regionList.size() > 0) {
            ResponseResult.success(response, regionList.get(0));
        } else {
            query.setCity("贵阳市");
            List<CjtCity> regionList1 = cjtCityService.selectList("", query);
            ResponseResult.success(response, regionList1.get(0));
        }
        return response;
    }

    /**
     * 根据出发地编码或城市，获取对应路线城市,为空取所有
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getRoadListByCode(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "getRoadListByCode");
        if (!checkRequireParms(parms, "serviceCode")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String startCode = ConvertUtil.parseString(parms.get("startCode"));
        String startCity = ConvertUtil.parseString(parms.get("startCity"));
        /*if (StringUtils.isBlank(startCode)) {
            return ResponseResult.exception(response, ErrorCode.CJT_START_CODE_NULL);
        }*/

        CjtRoad query = new CjtRoad();
        query.setEnabled(true);
        if (!TextUtils.isEmpty(startCode)) {
            query.setStartCode(startCode);
        }
        if (!TextUtils.isEmpty(startCity)) {
            query.setStartCity(startCity);
        }
        Sort sort = new Sort(Sort.Direction.ASC, "start_code");
        List<CjtRoad> regionList = cjtRoadService.selectList("", query, sort);
        ResponseResult.success(response, regionList);
        return response;
    }

    /**
     * 根据出发地编码，获取对应路线城市,为空取所有
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getRoadInfo(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "getRoadInfo");
        if (!checkRequireParms(parms, "startCity", "endCity")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String startCity = ConvertUtil.parseString(parms.get("startCity"));
        String endCity = ConvertUtil.parseString(parms.get("endCity"));
        if (StringUtils.isBlank(startCity)) {
            return ResponseResult.exception(response, ErrorCode.CJT_START_CODE_NULL);
        }
        if (StringUtils.isBlank(endCity)) {
            return ResponseResult.exception(response, ErrorCode.CJT_START_CODE_NULL);
        }
        CjtRoad query = new CjtRoad();
        query.setEnabled(true);
        query.setStartCity(startCity);
        query.setEndCity(endCity);

        CjtRoad cjtRoad = cjtRoadService.selectOne("", query);
        ResponseResult.success(response, cjtRoad);
        return response;
    }


    /**
     * 获取城际通司机排班列表
     * startcode 出发城市
     * endcode 到达城市
     * startTime 出发日期：格式 yyyy-MM-dd
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getSchedulList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "getSchedulList");
        if (!checkRequireParms(parms, "startCity", "endCity", "startTime")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String startCity = ConvertUtil.parseString(parms.get("startCity"));
        String endCity = ConvertUtil.parseString(parms.get("endCity"));
        String startTime = ConvertUtil.parseString(parms.get("startTime"));
        if (StringUtils.isBlank(startCity)) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        if (StringUtils.isBlank(endCity)) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        if (StringUtils.isBlank(startTime)) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        //查询路线id
        CjtRoad queryroad = new CjtRoad();
        queryroad.setEnabled(true);
        queryroad.setStartCity(startCity);
        queryroad.setEndCity(endCity);
        CjtRoad cjtRoad = cjtRoadService.selectOne("", queryroad);
        if (cjtRoad == null) {
            return ResponseResult.exception(response, ErrorCode.CJT_SCHEDUL_EMPTY);
        }

        long time = DateUtil.StringtoDate(startTime, DateUtil.yyyyMMdd).getTime() / 1000;
        CjtSchedul query = new CjtSchedul();
        query.setTime(time);
        query.setRoadId(cjtRoad.getId());
        Sort sort = new Sort(Sort.Direction.ASC, "go_time");
        List<CjtSchedul> regionList = cjtSchedulService.selectList("", query, sort);
        ResponseResult.success(response, regionList);
        return response;
    }


    /**
     * 用户提交城际通订单
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @paramschedulId 排班id
     * @paramstartLocation 出发地点
     * @paramstartLon 出发地点经度
     * @paramstartLat 出发地点纬度
     * @paramendLocation 目的地点
     * @paramendLon 目的地点经度
     * @paramendLat 目的地点纬度
     * @paramcrewCount 乘客数量
     * @paramcontactName 联系人
     * @paramcontactPhone 联系电话
     * @paramremark 备注
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject userPublishCjt(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "userPublishCjt");
        //参数检验
        if (!checkRequireParms(parms, "openId", "schedulId", "startLocation",
                "startLon", "startLat", "endLocation", "endLon", "endLat",
                "crewCount", "contactPhone")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        Long schedulId = ConvertUtil.parseLong(parms.get("schedulId"), 0);
        String startLocation = ConvertUtil.parseString(parms.get("startLocation"));
        Double startLon = ConvertUtil.parseDouble(parms.get("startLon"));
        Double startLat = ConvertUtil.parseDouble(parms.get("startLat"));
        String endLocation = ConvertUtil.parseString(parms.get("endLocation"));
        Double endLon = ConvertUtil.parseDouble(parms.get("endLon"));
        Double endLat = ConvertUtil.parseDouble(parms.get("endLat"));
        String contactPhone = ConvertUtil.parseString(parms.get("contactPhone"));
        String remark = ConvertUtil.parseString(parms.get("remark"));
        String contactName = ConvertUtil.parseString(parms.get("contactName"));
        Integer crewCount = ConvertUtil.parseInt(parms.get("crewCount"), 1);


        //用户openId和司机openId
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (schedulId < 1) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        if (StringUtils.isBlank(contactPhone)) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        if (crewCount < 1) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        //出发地点为空
        if (StringUtils.isBlank(startLocation) ||
                startLon == null || startLon == 0 ||
                startLat == null || startLat == 0) {
            return ResponseResult.exception(response, ErrorCode.BC_START_EMPTY);
        }
        //目的地点为空
        if (StringUtils.isBlank(endLocation) ||
                endLon == null || endLon == 0 ||
                endLat == null || endLat == 0) {
            return ResponseResult.exception(response, ErrorCode.BC_END_EMPTY);
        }

        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }

        //判断用户是否已经有了未完成的包车行程
        int status = TripStatus.Publish.getValue()
                | TripStatus.WaitingPay.getValue();
        ServiceTrip query = new ServiceTrip();
        query.setServiceCode(ServiceCode.CJT.getCode());
        query.setOpenId(openId);
        query.setStatus(status);
        long count = cJTServiceTripService.selectCount("", query);
        if (count > 0) {
            return ResponseResult.exception(response, ErrorCode.CJT_HAS_NOT_FINISHED_TRIP);
        }
        //查询排班
        CjtSchedul queryschedul = new CjtSchedul();
        queryschedul.setId(schedulId);
        CjtSchedul cjtSchedul = cjtSchedulService.selectOne("", queryschedul);
        if (cjtSchedul == null) {
            return ResponseResult.exception(response, ErrorCode.CJT_SCHEDUL_EMPTY);
        }
        if (cjtSchedul.getSeats() != null) {
            crewCount = Math.max(crewCount, 1);
            crewCount = Math.min(crewCount, cjtSchedul.getSeats());
        }
        //查询路线
        CjtRoad queryroad = new CjtRoad();
        queryroad.setId(cjtSchedul.getRoadId());
        CjtRoad cjtRoad = cjtRoadService.selectOne("", queryroad);
        if (cjtRoad == null) {
            return ResponseResult.exception(response, ErrorCode.CJT_ROAD_EMPTY1);
        }

        //查询路线所属公司
        Companypermit companyquery = new Companypermit();
        companyquery.setCompanyId(cjtRoad.getCompanyId());
        Companypermit companypermit = companypermitService.selectOne("", companyquery);

        //每日最多取消10次
        /*int cancelstatus = TripStatus.UserCancel.getValue()
                | TripStatus.Expired.getValue();
        ServiceTrip cancelquery = new ServiceTrip();
        cancelquery.setServiceCode(ServiceCode.CJT.getCode());
        cancelquery.setOpenId(openId);
        cancelquery.setStatus(cancelstatus);
        long cancelcount = cJTServiceTripService.selectCount("", query);
        if (cancelcount > Consts.CJT_USERCANCEL_COUNT) {
            return ResponseResult.exception(response, ErrorCode.BC_OVER_MAX_CANCEL_TIMES);
        }*/

        //查询司机行程是否存在
        ServiceTrip driverquery = new ServiceTrip();
        driverquery.setSchedulId(cjtSchedul.getId());
        driverquery.setServiceCode(ServiceCode.CJT.getCode());
        driverquery.setUserType(PlatformUserType.DRIVER_USER.getValue());
        driverquery.setDriverOpenId(cjtSchedul.getDriverOpenid());
        ServiceTrip serviceTrip = cJTServiceTripService.selectOne("", driverquery);
        if (serviceTrip == null) {
            return ResponseResult.exception(response, ErrorCode.CJT_DRIVER_TRIP_NULL);
        }

        //总费用
        double totalFee = ConvertUtil.toFiexd(cjtRoad.getPrice() * crewCount);

        String tripNo = SystemUtil.generateOrderNo(TripNoType.CJT.getPrefix());
        Boolean success = false;
        try {
            String time = DateUtil.longToStr(cjtSchedul.getTime() * 1000, "yyyy-MM-dd");
            Long lGoTime = SystemUtil.stringToSeconds(time + " " + cjtSchedul.getGoTime(), "yyyy-MM-dd HH:mm");
            ServiceTrip entity = new ServiceTrip();
            entity.setTripNo(tripNo);
            entity.setServiceCode(ServiceCode.CJT.getCode());
            entity.setUserType(PlatformUserType.CLIENT_USER.getValue());
            entity.setOpenId(openId);
            entity.setRoadId(cjtSchedul.getRoadId());
            entity.setSchedulId(schedulId);
            entity.setStartLocation(startLocation);
            entity.setStartLon(startLon);
            entity.setStartLat(startLat);
            entity.setEndLocation(endLocation);
            entity.setEndLon(endLon);
            entity.setEndLat(endLat);
            entity.setGoTime(lGoTime);
            entity.setCarSeats(cjtSchedul.getSeats() - 1);
            entity.setCrewCount(crewCount);
            entity.setCreateTime(SystemUtil.getAllSeconds());
            entity.setStatus(TripStatus.WaitingPay.getValue());
            entity.setDistance(0.0);
            entity.setDuration(0.0);
            entity.setHasAsign(false);
            entity.setHasComment(false);
            entity.setBillingMode(BillingMode.MakePrice.getValue());
            entity.setDriverOpenId(cjtSchedul.getDriverOpenid());
            entity.setCompanyId(cjtRoad.getCompanyId());
            if (companypermit != null) {
                entity.setAreaCode(companypermit.getAddress() + "");
            }
            entity.setRemark(cjtRoad.getFromTo());
            //对费用进行四舍五入
            entity.setPayFee(totalFee);
            //entity.setDepositPayFee(tmpDepositPayFee);
            success = cJTServiceTripService.publish("", entity, serviceTrip, cjtRoad.getPrice());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            query = new ServiceTrip();
            query.setTripNo(tripNo);
            ServiceTrip trip = cJTServiceTripService.selectByKey("", query);
            ResponseResult.success(response, trip);
        } else {
            ResponseResult.exception(response, ErrorCode.BC_PUBLISH_TRIP_FAILED);
        }

        return response;
    }

    /**
     * 用户取消城际通行程
     *
     * @param parms
     * @return
     * @parampenId 用户openId
     * @paramtripNo 包车行程单号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject userCancelCjt(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "userCancelCjt");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        //必须是自己的行程
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        query.setOpenId(openId);
        query.setServiceCode(ServiceCode.CJT.getCode());
        query.setUserType(PlatformUserType.CLIENT_USER.getValue());
        ServiceTrip trip = cJTServiceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.BC_TRIP_NOT_EXIST);
        }
        //取消规则。
        //12小时前，全额退款
        //2-12小时， 按票面金额20%计收退费手续费
        //发车前2小时内，  按票面金额80%计收退费手续费
        //发车后，不进行退款
        int tripStatus = TripStatus.WaitingPay.getValue()
                + TripStatus.Payed.getValue();
        //能取消的行程状态值(待支付，已支付)
        if ((trip.getStatus() & tripStatus) != trip.getStatus()) {
            return ResponseResult.exception(response, ErrorCode.BC_STATUS_ERROR);
        }

        Boolean success = false;
        try {
            success = cJTServiceTripService.userCancel("", trip, user, 1);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            query = new ServiceTrip();
            query.setTripNo(tripNo);
            ServiceTrip result = cJTServiceTripService.selectByKey("", query);

            response = ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.BC_USER_CANCEL_TRIP_FAILED);
        }
        return response;
    }

    /**
     * 司机发布城际通行程
     *
     * @param parms
     * @return
     * @paramopenId司机openId
     * @paramserviceCode 服务业务代码
     * @paramstartLocation 出发地点
     * @paramstartLon 出发地点经度
     * @paramstartLat 出发地点纬度
     * @paramendLocation 目的地点
     * @paramendLon 目的地点经度
     * @paramendLat 目的地点纬度
     * @paramgoTime 出发时间 时间格式yyyy-MM-dd HH:mm:ss
     * @paramcrewCount 默认已有乘客数
     * @paramroadId 行程路线，专线拼车业务时必须填，其它可以为空
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverPublishCjt(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "driverPublishCjt");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode", "startLocation", "startLon", "startLat",
                "endLocation", "endLon", "endLat", "goTime", "crewCount", "schedulId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        String startLocation = ConvertUtil.parseString(parms.get("startLocation"));
        Double startLon = ConvertUtil.parseDouble(parms.get("startLon"));
        Double startLat = ConvertUtil.parseDouble(parms.get("startLat"));
        String endLocation = ConvertUtil.parseString(parms.get("endLocation"));
        Double endLon = ConvertUtil.parseDouble(parms.get("endLon"));
        Double endLat = ConvertUtil.parseDouble(parms.get("endLat"));
        String goTime = ConvertUtil.parseString(parms.get("goTime"));
        Integer crewCount = ConvertUtil.parseInt(parms.get("crewCount"));
        Long schedulId = ConvertUtil.parseLong(parms.get("schedulId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        if (StringUtils.isBlank(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_EMPTY);
        }
        //出发地点为空
        if (StringUtils.isBlank(startLocation) ||
                startLon == null || startLon == 0 ||
                startLat == null || startLat == 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_START_EMPTY);
        }
        //目的地点为空
        if (StringUtils.isBlank(endLocation) ||
                endLon == null || endLon == 0 ||
                endLat == null || endLat == 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_END_EMPTY);
        }
        //出发时间为空
        if (StringUtils.isBlank(goTime)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_GO_TIME_EMPTY);
        }
        //专线拼车服务业务的时候要检查roadId
        if (ServiceCode.CJT.getCode().equals(serviceCode) && schedulId < 1) {
            return ResponseResult.exception(response, ErrorCode.TRIP_ROAD_EMPTY);
        }

        //两点间路线距离估算
        RouteMatrixRequestParms request = new RouteMatrixRequestParms.Builder()
                .setOrigins(String.format("%s,%s", startLat, startLon))
                .setDestinations(String.format("%s,%s", endLat, endLon))
                .setOutput("json")
                .setTactics("11")
                .setAk(Consts.BAIDU_MAP_AK)
                .build();

        RouteMatrixResponseParmsResult routeMatrixResult = RouteMatrixApi.driving(request);
        //无法估计距离
        if (routeMatrixResult == null || routeMatrixResult.getDistance().getValue() == null) {
            return ResponseResult.exception(response, ErrorCode.ROUTE_MATRIX_FAILED);
        }

        //查询排班
        CjtSchedul queryschedul = new CjtSchedul();
        queryschedul.setId(schedulId);
        CjtSchedul cjtSchedul = cjtSchedulService.selectOne("", queryschedul);
        if (cjtSchedul == null) {
            return ResponseResult.exception(response, ErrorCode.CJT_SCHEDUL_EMPTY);
        }
        if (cjtSchedul.getSeats() != null) {
            crewCount = Math.max(crewCount, 1);
            crewCount = Math.min(crewCount, cjtSchedul.getSeats());
        }
        //查询路线
        CjtRoad queryroad = new CjtRoad();
        queryroad.setId(cjtSchedul.getRoadId());
        CjtRoad cjtRoad = cjtRoadService.selectOne("", queryroad);
        if (cjtRoad == null) {
            return ResponseResult.exception(response, ErrorCode.CJT_ROAD_EMPTY1);
        }

        ServiceTrip entity = new ServiceTrip();
        Boolean success = false;
        try {
            double distance = routeMatrixResult.getDistance().getValue();
            double duration = routeMatrixResult.getDuration().getValue();

            Long lGoTime = SystemUtil.stringToSeconds(goTime, "yyyy-MM-dd HH:mm:ss");
            entity.setTripNo(SystemUtil.generateOrderNo(TripNoType.TRIP.getPrefix()));
            entity.setOpenId(openId);
            entity.setServiceCode(serviceCode);
            entity.setUserType(PlatformUserType.DRIVER_USER.getValue());
            entity.setDriverOpenId(openId);
            entity.setRoadId(cjtSchedul.getRoadId());
            entity.setSchedulId(schedulId);
            entity.setStartLocation(startLocation);
            entity.setStartLon(startLon);
            entity.setStartLat(startLat);
            entity.setEndLocation(endLocation);
            entity.setEndLon(endLon);
            entity.setEndLat(endLat);
            entity.setCreateTime(SystemUtil.getAllSeconds());
            entity.setGoTime(lGoTime);
            entity.setStatus(TripStatus.Publish.getValue());
            entity.setCrewCount(crewCount);
            entity.setCarSeats(driver.getCarSeats());
            entity.setCarRank(driver.getCarRank());
            entity.setHasAsign(false);
            entity.setHasComment(false);
            //单位米
            entity.setDistance(distance);
            //单位秒
            entity.setDuration(duration);
            entity.setCompanyId(cjtRoad.getCompanyId());
            entity.setAreaCode(cjtRoad.getStartCode());
            entity.setRoadId(cjtRoad.getId());

            //司机发布行程
            success = serviceTripService.driverPublishTrip("", entity);

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            response = ResponseResult.success(response, entity);
        } else {
            response = ResponseResult.exception(response, ErrorCode.TRIP_PUBLISH_FAILED);
        }

        return response;
    }

    /**
     * 取消司机城际通行程
     *
     * @param parms
     * @return
     * @parampenId 用户openId
     * @paramtripNo 包车行程单号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject driverCancelCjt(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "driverCancelCjt");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        //必须是自己的行程
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        query.setOpenId(openId);
        query.setServiceCode(ServiceCode.CJT.getCode());
        query.setUserType(PlatformUserType.DRIVER_USER.getValue());
        ServiceTrip trip = cJTServiceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.BC_TRIP_NOT_EXIST);
        }

        //判断是否有乘客下单，
        ServiceTrip userquery = new ServiceTrip();
        userquery.setServiceCode(ServiceCode.CJT.getCode());
        userquery.setUserType(PlatformUserType.CLIENT_USER.getValue());
        userquery.setSchedulId(trip.getSchedulId());
        List<ServiceTrip> usertrip = cJTServiceTripService.selectList("", query);
        if (usertrip != null && usertrip.size() > 0) {
            return ResponseResult.exception(response, ErrorCode.CJT_DRIVER_CANCEL_FAILE);
        }

        int row = 0;
        try {
            row = cJTServiceTripService.deleteByKey("", trip);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (row > 0) {
            response = ResponseResult.success(response, true);
        } else {
            response = ResponseResult.exception(response, ErrorCode.CJT_USER_CANCEL_TRIP_FAILED);
        }
        return response;
    }

    /**
     * 司机获取城际通乘客订单列表
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramserviceCode 服务业务代码
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject getTripListByCjt(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("cjt", "getTripListByCjt");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //判断司机的行程是否存在
        ServiceTrip tripQuery = new ServiceTrip();
        tripQuery.setTripNo(tripNo);
        tripQuery.setDriverOpenId(openId);

        ServiceTrip trip = serviceTripService.selectOne("", tripQuery);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }

        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(tripNo);
        crewsQuery.setDriverOpenId(openId);
        List<ServiceTripCrews> crewsList = serviceTripCrewsService.selectList("", crewsQuery);
        //用户行程单号列表
        List<String> tripNoList = new ArrayList<String>();
        if (crewsList != null && !crewsList.isEmpty()) {
            for (ServiceTripCrews item : crewsList) {
                tripNoList.add(item.getCrewTripNo());
            }
        }
        List<ServiceTrip> userTripList = serviceTripService.selectListIn("", null, tripNoList);
        response = ResponseResult.success(response, userTripList);
        return response;
       /* ServiceTrip crewsQuery = new ServiceTrip();
        crewsQuery.setSchedulId(trip.getSchedulId());
        crewsQuery.setDriverOpenId(openId);
        crewsQuery.setUserType(PlatformUserType.CLIENT_USER.getValue());
        crewsQuery.setPayStatus(TradePayStatus.TRADE_SUCCESS.getValue());

        Sort sort = new Sort(Sort.Direction.ASC, "create_time");
        List<ServiceTrip> crews = serviceTripService.selectList("", crewsQuery, sort);
        response = ResponseResult.success(response, crews);
        return response;*/
    }
}
